google.load('search', '1');

org.mentalsmash.asksusanna.Susanna = function(options) {
	
	var conf = new org.mentalsmash.asksusanna.SusyConf(options);
	
	var gui = new org.mentalsmash.asksusanna.gui.GUI(conf);
	
	return {
		'analyze' : function(phraseStr) {
			var phrase = new org.mentalsmash.asksusanna.Phrase(phraseStr,conf);
			var subphrases = phrase.getSubphrases();
			//alert(subphrases.join(' - '));
			var counter = subphrases.length;
			var susy = this;
			$(subphrases).each(function(i,subph){
				susy.query(subph,function(hits){
					phrase.setSubphraseHits(subph,hits);
					counter--;
					if (counter == 0) {
						phrase.computeScores();
						gui.showPhraseResults(phrase);
					}
				});
			});
		},

		'query' : function(phrase, callback) {
			var ws = new google.search.WebSearch();
			ws.setResultSetSize(1);
			ws.setNoHtmlGeneration();

			ws.setSearchCompleteCallback(this, function(ws) {

				if (ws.cursor) {
					callback(ws.cursor.estimatedResultCount);
				} else {
					callback(0);
				}
			},[ws])
			ws.execute("\""+phrase+"\"");
		}


	};
}

org.mentalsmash.asksusanna.Susanna.main = function() {
	var susy = new org.mentalsmash.asksusanna.Susanna();

	var handler = function(e){
		var input =  $('#search > input[name=phrase]');
		var query = input.val();
		susy.analyze(query);
		return false;
	};

	$('#search').submit(handler);
}
